import http from 'axios'
import router from '../router'
import {Message} from 'element-ui'

let UrlConfig = {
  user_login: 'api/v1.0/user/login',
  music_base: 'https://www.lqgjm.work/music/',
  music_random: '/api/v1.0/music/random',
  book_list: 'api/v1.0/book/list',
  book_type: 'api/v1.0/book/type',
  book_content: 'api/v1.0/book/content',
  Content_Type: 'application/x-www-form-urlencoded'
}
export default UrlConfig

// http request 拦截器
http.interceptors.request.use(
  config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
    config.data = JSON.stringify(config.data)
    config.headers = {
      'Content-Type': UrlConfig.Content_Type,
      'token': localStorage.getItem('token')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// http response 拦截器
http.interceptors.response.use(
  response => {
    switch (response.data.status) {
      case -1:
        Message.error(response.data.msg)
        return null
      case -2:
        Message.error('请重新登录')
        localStorage.clear()
        router.push({
          path: '/'
        })
        return null
      default:
        return response
    }
  },
  error => {
    return Promise.reject(error)
  }
)

/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise}
 */

export function fetch (url, params = {}) {
  return new Promise((resolve, reject) => {
    http.get(url, {
      params: params
    })
      .then(response => {
        resolve(response)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    http.post(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch (url, data = {}) {
  return new Promise((resolve, reject) => {
    http.patch(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put (url, data = {}) {
  return new Promise((resolve, reject) => {
    http.put(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}
